﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;

namespace ExBug
{
    public partial class AnaliticeConturiAAFrm : FrmRezumat
    {
        private String _Articol = String.Empty;
        private String titlu = String.Empty;
        public String Articol
        {
            get { return _Articol; }
            set
            {
                _Articol = value;
                Text = titlu + _Articol;
            }
        }
        private Boolean GenerareLaToateArticolele = false;

        public AnaliticeConturiAAFrm(ModuleClass mInfo,Boolean generareToateArticolele)
            : base(mInfo)
        {
            InitializeComponent();
            workConnString = mInfo.workConnectionString;
            titlu = this.Text;
            GenerareLaToateArticolele = generareToateArticolele;
            areArticoleGenColumn.Visible = GenerareLaToateArticolele;

        }

        private void AnaliticeConturiAAFrm_Load(object sender, EventArgs e)
        {

            SqlConnection con = DeschideConexiune(workConnString);
            this.exBug_ConturiSpecialeTableAdapter.Connection = con;
            if(GenerareLaToateArticolele)
                exBug_ConturiSpecialeTableAdapter.FillByTipuri(this.eSRPDataSet.exBug_ConturiSpeciale, ModuleInfo.CodUnitate, "AA");
            else
                this.exBug_ConturiSpecialeTableAdapter.FillByAA(this.eSRPDataSet.exBug_ConturiSpeciale, ModuleInfo.CodUnitate);
            InchideConexiune(con);
            GetConturi();
            AddButton("Salvare", global::ERPStudio.Properties.Resources.salvare, Salvare1, ToolStripItemAlignment.Right, true);

        }

        private void Salvare1(object sender, EventArgs e)
        {
            if (GenerareLaToateArticolele)
            {
                int i=0;
                SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "[balcon_GenerareAnaliticeArticoleAlineate]";
                foreach (DataGridViewRow dr in conturiSpecialeDGV.Rows)
                {
                    if (Convert.ToInt32(dr.Cells["OperatieColumn"].Value) == 1)
                    {
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add(new SqlParameter("Cont", dr.Cells["ContColumn"].Value.ToString()));
                        cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
                        cmd.ExecuteNonQuery();   
                        i++;
                    }
                }
                InchideConexiune(cmd.Connection);
                MessageBox.Show("Au fost generate articole si aliniate pentru " + i.ToString() + " conturi!");
                Close();
                return;
            }

            foreach (DataGridViewRow dr in conturiSpecialeDGV.Rows)
            {
                if (Convert.ToInt32(dr.Cells["OperatieColumn"].Value) == 1)
                {
                    // se adauga contul
                    AdaugaAnalitic(_Articol, dr.Cells["ContColumn"].Value.ToString());
                    // ca si cum ar fi acolo
                    conturiSpecialeDGV["OperatieColumn", dr.Index].Value = 0;
                }
                if (Convert.ToInt32(dr.Cells["OperatieColumn"].Value) == 2)
                {
                    // se adauga contul
                    StergeAnalitic(_Articol, dr.Cells["ContColumn"].Value.ToString());
                    // ca si cum ar fi acolo
                    conturiSpecialeDGV["OperatieColumn", dr.Index].Value = 0;
                }
            }
            SetStatus("S-au salvat datele la: " + DateTime.Now.ToString());
        }

        private Boolean AdaugaAnalitic(string Analitic, String Cont)
        {
            //se adauga analitic la cont
            // se verifica care este parintele
            SqlConnection con = DeschideConexiune(workConnString);
            SqlCommand com = new SqlCommand("Select AAParinte From [ArticoleAliniate] where ArtAl='" + Analitic + "'",
                con);
            String ContParinte = com.ExecuteScalar().ToString();


            // verifica daca exista contul 
            com.CommandText = "SELECT Cont FROM [Conturi] WHERE Cont='" + Cont + "." + Analitic + "'";
            Object ContExistent = com.ExecuteScalar();

            //daca contul exista nu facem nimic
            if (ContExistent != null && ContExistent.ToString() == Cont + "." + Analitic)
                return true;

            if (ContParinte != "N/A")
                if (!AdaugaAnalitic(ContParinte, Cont))
                    return false;
            // daca s-a reusit adaugarea parintelui
            com.CommandText = "INSERT INTO [Conturi] " +
             "([Cont],[CodUnitate],[Denumire],[Tip],[Terminal],[ContParinte],[EsteAnalitic],[DebitInitial],[CreditInitial],[DebitPrecedent],[CreditPrecedent],[Categorie],[RulajDebit],[RulajCredit]) " +
             " SELECT '" + Cont + ".' + a.[ArtAl] AS [Cont]" +
             ",a.[CodUnitate],a.[Denumire],b.[Tip],1 AS [Terminal],'" + (ContParinte != "N/A" ? (Cont + "." + ContParinte) : Cont) + "' AS [ContParinte],1 AS [EsteAnalitic],0 AS [DebitInitial],0 AS [CreditInitial] ,0 AS [DebitPrecedent],0 AS [CreditPrecedent],b.[Categorie],0 AS [RulajDebit],0 AS [RulajCredit] " +
             " FROM [ArticoleAliniate] a,[Conturi] b WHERE a.[CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND a.[ArtAl]='" + Analitic + "' AND b.[CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND b.[Cont]='" + Cont + "'";

            com.ExecuteNonQuery();
            InchideConexiune(con);

            return true;
        }


        private Boolean StergeAnalitic(string Analitic, String Cont)
        {
            //se adauga analitic la cont
            // se verifica care este parintele
            SqlConnection con = DeschideConexiune(workConnString);
            SqlCommand com = new SqlCommand("Select AAParinte From [ArticoleAliniate] where ArtAl='" + Analitic + "'",
                con);
            String ContParinte = com.ExecuteScalar().ToString();


            // verifica daca exista contul 
            com.CommandText = "SELECT Cont FROM [Conturi] WHERE Cont='" + Cont + "." + Analitic + "'";
            Object ContExistent = com.ExecuteScalar();

            //daca contul nu exista nu facem nimic
            if (ContExistent == null)
                return true;

            // daca s-a reusit adaugarea parintelui
            try
            {
                com.CommandText = "DELETE FROM [Conturi] " +
                 "WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND [Cont]='" + Cont + "." + Analitic + "'";

                com.ExecuteNonQuery();
            }
            catch
            {
                //daca da eroare asta e...
            }

            if (ContParinte != "N/A")
                if (!StergeAnalitic(ContParinte, Cont))
                    return false;


            InchideConexiune(con);

            return true;
        }


        private void GetConturi()
        {
            SqlConnection con = DeschideConexiune(workConnString);
            SqlCommand com = new SqlCommand("Select REPLACE(Cont,'." + _Articol.ToString() + "','') [Cont] from [Conturi] where Cont like '%." + _Articol.ToString() + "'",
                con);
            SqlDataReader Conturi = com.ExecuteReader();
            while (Conturi.Read())
            {
                Int32 rand = EsteCont(Conturi["Cont"].ToString());
                if (rand != -1)
                {
                    //marchaeza randul
                    conturiSpecialeDGV.Rows[rand].Cells["AnaliticColumn"].Value = true;
                }
            }
            Conturi.Close();
            InchideConexiune(con);
        }

        private Int32 EsteCont(string cont)
        {
            foreach (DataGridViewRow dr in conturiSpecialeDGV.Rows)
            {
                if (dr.Cells[contColumn.Index].Value.ToString() == cont)
                    return dr.Index;
            }
            return -1;
        }

        private void conturiSpecialeDGV_Click(object sender, EventArgs e)
        {

        }

        private void conturiSpecialeDGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == AnaliticColumn.Index)
            {
                //valoarea anterioara clicului
                Boolean val = Convert.ToBoolean(conturiSpecialeDGV["AnaliticColumn", e.RowIndex].Value);
                Int32 valOp = Convert.ToInt32(conturiSpecialeDGV["OperatieColumn", e.RowIndex].Value);
                if (valOp == 0 && val == false)
                {
                    //se va adauga analitic
                    conturiSpecialeDGV["OperatieColumn", e.RowIndex].Value = 1;
                    return;
                }
                if (valOp != 0 && val == true)
                {
                    //se va adauga nimic
                    conturiSpecialeDGV["OperatieColumn", e.RowIndex].Value = 0;
                    return;
                }
                if (valOp == 0 && val == true)
                {
                    //se va sterge
                    conturiSpecialeDGV["OperatieColumn", e.RowIndex].Value = 2;
                    return;
                }


            }
        }
    }
}
